package com.ugoodtech.mdcc.web.controller;


import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.DepartmentRepository;
import com.ugoodtech.mdcc.core.repository.NationRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import com.ugoodtech.mdcc.core.service.NationService;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright © 2013 All Rights Reserved, Ugood Technology, Inc.
 */
//@ApiIgnore
@Controller
@RequestMapping("/nation")
public class NationController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(NationController.class);

    @Autowired
    private NationService nationService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private NationRepository nationRepository;


    @ApiOperation("获取当登陆用户的省份")
    @RequestMapping(value = "/getMyProvinces", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getMyProvinces(Long loginUserId) {
        User clientUser = userRepository.findOne(loginUserId);
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
//        if (clientUser.getUserType().equals(UserType.dealers)) {
        return getProvinces(false);
//        }
//        List<LabelValue> labelValues = new ArrayList<>();
//        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
//        List<Nation> nationList = userProfile.getNationList();
//        if (nationList == null || nationList.size() <= 0) {
//            nationList = (List<Nation>) nationRepository.findAll();
//            labelValues = toLableValue(nationList);
//            return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, false));
//        }
//        if (null != nationList) {
//            labelValues = toLableValue(nationList);
//        }
//        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, false));
    }

    private List<LabelValue> toLableValue(List<Nation> nationList) {
        List<LabelValue> labelValues = new ArrayList<>();
        for (Nation nation : nationList) {
            if (nation.getProvince().equals("中华人民共和国")) {
                continue;
            }
            LabelValue labelValue = new LabelValue(nation.getProvince(), nation.getCode() + "");
            labelValues.add(labelValue);
        }
        return labelValues;
    }


    @RequestMapping(value = "/getProvinces", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getProvinces(
            boolean addAll
    ) {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getProvinces---------------");
        }
        Iterable<Nation> nations = nationService.findAllProvinces();
        List<LabelValue> labelValues = new ArrayList<>();
        User systemUser = this.getCurrentUser();
        Nation city = null;
        if (null != nations) {
            for (Nation nation : nations) {
                if (!nation.getProvince().equals("中华人民共和国")) {
                    LabelValue labelValue = new LabelValue(nation.getProvince(), nation.getCode() + "");
                    labelValues.add(labelValue);
                }
            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));
    }

    @RequestMapping(value = "/getCities", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getCities(
            String code,
            @RequestParam(required = false) Boolean addAll
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getCities---------------");
        }
        if (null == addAll) {
            addAll = false;
        }
        Iterable<Nation> nations = nationService.findCitiesInProvince(code);
        List<LabelValue> labelValues = new ArrayList<>();
        User systemUser = this.getCurrentUser();
        String provinceCode = "";
        if (null != nations) {
            for (Nation nation : nations) {
                if (nation.getCode().equals(provinceCode) || "".equals(provinceCode)) {
                    LabelValue labelValue = new LabelValue(nation.getCity(), nation.getCode() + "");
                    labelValues.add(labelValue);
                }
            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));
    }

    @RequestMapping(value = "/getDistricts", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getDistricts(
            String code,
            @RequestParam(required = false) Boolean addAll
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getDistricts---------------");
        }
        if (null == addAll) {
            addAll = false;
        }
        Iterable<Nation> nations = nationService.findDistrictsInCity(code);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != nations) {
            for (Nation nation : nations) {
                LabelValue labelValue = new LabelValue(nation.getDistrict(), nation.getCode() + "");
                labelValues.add(labelValue);
            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));
    }

    @ApiOperation("获取街道")
    @RequestMapping(value = "/getStreets", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getStreets(
            @ApiParam("区的code") @RequestParam String code,
            @RequestParam(required = false) Boolean addAll
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------getDistricts---------------");
        }
        if (null == addAll) {
            addAll = false;
        }

        Iterable<Nation> nations = nationService.findStreetsInDistrict(code);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != nations) {
            for (Nation nation : nations) {
                LabelValue labelValue = new LabelValue(nation.getStreet(), nation.getCode() + "");
                labelValues.add(labelValue);
            }
        }
        return JsonResponse.successResponseWithData(this.getLabelValueArrayForString(labelValues, addAll));

    }

    @Autowired
    private DepartmentRepository departmentRepository;

    @ApiOperation("获取省份/品牌下拉框")
    @RequestMapping(value = "/getDeparmentProvince", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getDeparmentProvince() {
        Iterable<Nation> nationList = nationService.findAllProvinces();
        StringBuffer stringBuffer = new StringBuffer();
        for (Nation nation : nationList) {
            String nationName = nation.getProvince();
            if (nationName.equals("中华人民共和国")) {
                continue;
            }
            stringBuffer.append(nationName + "望达," + nationName + "新劲莱顺,");
        }
        String[] nationArray = stringBuffer.toString().split(",");
        return JsonResponse.successResponseWithData(nationArray);
    }

    @ApiOperation("根据部门获取省份")
    @RequestMapping(value = "/getNation", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getNation(@ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId) {
        if (departmentId == null || departmentId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "参数错误");
        }
        Department department = departmentRepository.findOne(departmentId);
        if (department == null) {
            return JsonResponse.successResponseWithData(new String[0]);
        }
        if (department.getParent() == null) {
            Iterable<Nation> nations = nationService.findAllProvinces();
            StringBuffer stringBuffer = new StringBuffer();
            for (Nation nation : nations) {
                if (nation.getProvince().equals("中华人民共和国")) {
                    continue;
                }
                stringBuffer.append(nation.getProvince() + ",");
            }
            String[] array = stringBuffer.toString().split(",");
            return JsonResponse.successResponseWithData(array);
        }
//        List<Nation> nationList = department.getNationList();
//        String[] nation = new String[nationList.size()];
//        for (int i = 0; i < nationList.size(); i++) {
//            nation[i] = nationList.get(i).getProvince();
//        }
        return JsonResponse.successResponseWithData("");
    }


}
